<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

use service\DataService;
use service\NodeService;
use think\Db;
use app\member\model\Cate;

// 应用公共文件

/**
 * 设备或配置系统参数
 * @param string $name 参数名称
 * @param bool $value 默认是null为获取值，否则为更新
 * @return string|bool
 */
function sysconf($name, $value = null)
{
    static $config = [];
    if ($value !== null) {
        list($config, $data) = [[], ['name' => $name, 'value' => $value]];
        return DataService::save('SystemConfig', $data, 'name');
    }
    if (empty($config)) {
        $config = Db::name('SystemConfig')->column('name,value');
    }
    return isset($config[$name]) ? $config[$name] : '';
}

/**
 * RBAC节点权限验证
 * @param string $node
 * @return bool
 */
function auth($node)
{
    return NodeService::checkAuthNode($node);
}

/**
 * [rstReturn 内部数据返回结果]
 * @param  string $success [成功信息]
 * @param  string $error   [失败信息]
 * @param  [type] $status  [处理数据结果]
 * @return [type]          [description]
 */
function rstReturn($status = false, $msg = '', $data = []){

    return ['status'=>$status,'msg'=>$msg,'data'=>$data];
}

/**
 * [doReturn 返回前端ajax处理数据结果]
 * @param  string $success [成功信息]
 * @param  string $error   [失败信息]
 * @param  [type] $status  [处理数据结果]
 * @return [type]          [description]
 */
function doReturn($success = '成功',$error = '失败',$status,$data = array(),$type = 'json',$header = array()){
    if($status !== false){
        $msg = array(
            "code" => 200,
            "msg" => $success,
            'data' => $data,
            'type' => $type,
            'header' => $header

        );
    }else{
        $msg = array(
            "code" => 0,
            "msg" => $error,
            "data" => $data,
            'type' => $type,
            'header' => $header
        );
    }
    return $msg;
}

/**
 * 加密盐值
 * @param  integer $length 长度
 * @return [type]          [description]
 */
function getSalt($length = 4){
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
    $salt ='';
    for($i=0;$i<$length;$i++){
        $salt .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }
    return $salt;
}

/**
 * 日期格式化
 * @param string $date 标准日期格式
 * @param string $format 输出格式化date
 * @return false|string
 */
function format_datetime($date, $format = 'Y年m月d日 H:i:s')
{
    return empty($date) ? '' : date($format, strtotime($date));
}


/**
 * 获取微信操作对象
 * @param string $type
 * @return \Wechat\WechatMedia|\Wechat\WechatMenu|\Wechat\WechatOauth|\Wechat\WechatPay|\Wechat\WechatReceive|\Wechat\WechatScript|\Wechat\WechatUser|\Wechat\WechatExtends|\Wechat\WechatMessage
 * @throws Exception
 */
function & load_wechat($type = '')
{
    static $wechat = [];
    $index = md5(strtolower($type));
    if (!isset($wechat[$index])) {
        $config = [
            'token'          => sysconf('wechat_token'),
            'appid'          => sysconf('wechat_appid'),
            'appsecret'      => sysconf('wechat_appsecret'),
            'encodingaeskey' => sysconf('wechat_encodingaeskey'),
            'mch_id'         => sysconf('wechat_mch_id'),
            'partnerkey'     => sysconf('wechat_partnerkey'),
            'ssl_cer'        => sysconf('wechat_cert_cert'),
            'ssl_key'        => sysconf('wechat_cert_key'),
            'cachepath'      => CACHE_PATH . 'wxpay' . DS,
        ];
        if(!class_exists('\Wechat\Loader')) {
            require VENDOR_PATH . 'zoujingli' . DIRECTORY_SEPARATOR . 'wechat-php-sdk' . DIRECTORY_SEPARATOR . 'Wechat' . DIRECTORY_SEPARATOR . 'Loader.php';
        }
        $Loader = new \Wechat\Loader();
        $wechat[$index] = $Loader::get($type, $config);
    }
    return $wechat[$index];
}

/**
 * UTF8字符串加密
 * @param string $string
 * @return string
 */
function encode($string)
{
    list($chars, $length) = ['', strlen($string = iconv('utf-8', 'gbk', $string))];
    for ($i = 0; $i < $length; $i++) {
        $chars .= str_pad(base_convert(ord($string[$i]), 10, 36), 2, 0, 0);
    }
    return $chars;
}

/**
 * UTF8字符串解密
 * @param string $string
 * @return string
 */
function decode($string)
{
    $chars = '';
    foreach (str_split($string, 2) as $char) {
        $chars .= chr(intval(base_convert($char, 36, 10)));
    }
    return iconv('gbk', 'utf-8', $chars);
}

/**
 * @param $password
 * @param $verify
 *
 * @return string
 */
function encryptPassword($password, $verify)
{
    return md5($password . $verify);
}


/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0,$adv=false) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if($adv){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}


/**
 * @return string
 * 返回一个token字符串
 */
function generateToken()
{
    $randChars = getRandChar(32);
    $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
    $salt = config('token_salt');

    return md5($randChars . $timestamp . $salt);
}

/**
 * @param $lenght
 *
 * @return string
 *
 * 生成一个定义长度的随机字符串
 */
function getRandChar($lenght)
{
    $randStr = "";
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;

    for ($i = 0; $i < $lenght; $i++) {
        $randStr .= $strPol[rand(0, $max)];
    }

    return $randStr;
}

function getiparea($ip)
{
    if (!$ip) {
        return false;
    }
    $url = 'http://ip.taobao.com/service/getIpInfo.php?ip=%s';
    $res = httpGet(sprintf($url, $ip));
    $res = json_decode($res, true);
    if ($res['code'] != 0) {
        return false;
    }

    return $res['data'];
}


/**
 * GET
 *
 * @param $url
 *
 * @return mixed
 */
function httpGet($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
}


function isMobile($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }

    ///^[1][3,4,5,7,8][0-9]{9}$/
    return preg_match('/^[1][2,3,4,5,6,7,8,9][0-9]{9}$/', $mobile) ? true : false;
}


function getSMSCode(){
    return rand(1000,9999);
}



/**
 * @param $templateId 短信模板id
 * @param $content    短信内容
 * @param $receiver   接收手机号码
 *
 * @return messageId
 */
function sendSMS($templateId, $content, $receiver) {
    if (is_string($receiver)) {
        $receiver = array($receiver);
    }
    if (!is_array($receiver) || empty($receiver)) {
        throw_exception('参数不正确');
    }

    vendor('smsClient');
    $config = ['ak' => '405706e7ad4a400eb99a050bab187189', 'sk' => 'd89682d633d14ed583078241fdcec369'];
    $content = $content;
    $client = new smsClient($config);

    return $client->messageSend('smsTpl:' . $templateId, $receiver, $content);
}

/**
 * 生成类别cate.js文件
 */
function updata_cate_date()
{
    $filename =  ROOT_PATH . '/Public/static/member/js/cate.js';
    $typeData = Cate::getCat();
    $str_mp = Cate::getJsArr($typeData);
    $str_mc = Cate::getSunArea($typeData);
    $res = $str_mp . $str_mc;

    file_put_contents($filename, $res);
//        $this->success("", "thumb.html");
}

// 不区分大小写的in_array实现
function in_array_case($value,$array){
    return in_array(strtolower($value),array_map('strtolower',$array));
}


function getimg($content){

    if(preg_match_all("/(href)=([\"|']?)([^ \"'>]+\.(rar|zip))\\2/i", $content, $matches)) {
        return $matches;
    }
}

//禁止ip
function http_transport($url, $params = array(), $method = 'POST')
{
    $opts = array(
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    );
    /* 根据请求类型设置特定参数 */
    switch(strtoupper($method)){
        case 'GET':
            $opts[CURLOPT_URL] = $url .'?'. http_build_query($params);
            break;
        case 'POST':
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
    }
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data  = curl_exec($ch);
    $err = curl_errno($ch);
    $errmsg = curl_error($ch);
    curl_close($ch);
    if ($err > 0) {
        // $this->error = $errmsg;
        return false;
    }else {
        return $data;
    }
}

//function get_white_ip(){
//    if(empty(Cache::get('white_ip'))){
//        $white_ip= http_transport('http://passport.qftouch.cn/api/ipwhite');
//        $white_ips=json_decode($white_ip,true);
//        Cache::set('white_ip',$white_ips,3600*48);
//    }
//    $data = Cache::get('white_ip');
//    return $data;
//}
